import requests
from urllib import request
import re

session = requests.session()
form = {
    'form_email': '1752570559@qq.com',
    'form_password': '1234qwer'
}

def login():
    login_url = 'https://accounts.douban.com/login'

    form = {
        'form_email' : '124@qq.com',   #輸入你的賬號
        'form_password' : '1234qwer'	#输入你的密码
    }

    response = session.post(login_url,data=form)
    response.encoding = response.apparent_encoding
    html = response.text
    if 'captcha_image' in html: # 有验证码
        captcha_pat = re.compile(r'id="captcha_image" src="(.+?)"')
        res = captcha_pat.search(html)
        captcha = res.group(1)
        request.urlretrieve(captcha,'douban.png')

        id_pat = re.compile(r'name="captcha-id" value="(.+?)"')
        res = id_pat.search(html)
        captcha_id = res.group(1)

        print(captcha,captcha_id)

        captcha = input('输入验证码')
        form['captcha-solution'] = captcha
        form['captcha-id'] = captcha_id

        response = session.post(login_url,data=form)
        response.encoding = response.apparent_encoding
        html = response.text

        if '个人主页' in html:
            home_url = "https://www.douban.com/mine/"
            response = session.get(home_url)
            response.encoding = response.apparent_encoding
            # print('个人主页地址',response.url)
            print('登陆成功')
            return response
    else:
        print('登陆成功')

# 修改签名
def update_sign(response,sign):
    edit_url = response.url + 'edit_signature'
    edit_url = edit_url.replace('/people/','/j/people/')
    print(edit_url)
    html = response.text
    ck_pat = re.compile(r'name="ck" value="(.+?)"')
    res = ck_pat.search(html)
    ck = res.group(1)

    form = {
        'ck' : ck,
        'signature' : sign
    }

    resp = session.post(edit_url,data=form)
    resp.encoding = resp.apparent_encoding
    print(resp.text)

if __name__ == '__main__':
    response = login()

    while True:
        choice = input('请选择：')
        if choice == '1':
            sign = input('输入签名：')
            update_sign(response,sign)
        elif choice == 'q':
            break
